import os
import fnmatch
from cStringIO import StringIO
from tokenize import generate_tokens
#import itertools
from time import sleep

#def imerge(a, b):
#    for i, j in itertools.izip(a,b):
#        yield i
#        yield j

def translate_key( path):
    # handle indexed items
    tokens = []
    for token in generate_tokens(StringIO(path.strip()).readline):
        if token[0] == 0:
            continue
        tokens.append(token)

    # first part should be a string
    assert tokens[0][0] == 1

    name = tokens[0][1]

    index = None

    if len(tokens) > 1:
        # second a open brace
        assert tokens[1][0] == 51, "Invalid config reference %s. Missing open brace." % path
        # then a number
        assert tokens[2][0] == 2, "Invalid config reference %s. Missing index." % path
        # finally a close brace
        assert tokens[3][0] == 51, "Invalid config reference %s. Missing close brace" % path

        index = int(tokens[2][1])
    return name, index

def translate_disk_name(config, disk):
    if not isinstance(disk, list):
        return _translate_disk_name(config, disk)

    ret = []
    for a_disk in disk:
        ret.append(_translate_disk_name(config, a_disk))
    return ret

def _translate_disk_name(config, disk):
    if disk.startswith('/') or disk.startswith('md'):
        return disk

    #if disk.startswith('md'):
    #    return disk
        #return os.path.realpath(os.path.join('/dev', 'md', disk))

    name, index = translate_key(disk)

    for disk_name_mapping in config.get_resources().iter_by_type('disk-name'):
        if name != disk_name_mapping.get_name():
            continue

        string = disk_name_mapping.get_device()
        if index is not None:
            string += str(index)


        return string

    raise Exception("Failed to get disk name mapping for %s" % disk)
